package it.controllocredito.backend.persistence.tables;

import java.sql.Timestamp;
import java.util.GregorianCalendar;
import java.util.Locale;

import it.controllocredito.backend.persistence.bean.Configuration;

import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

public abstract class ConfigurationTable {

    private static final String log_class_name = "ConfigurationTable";

    private static final String TABLE_NAME = "CONFIGURATION";

    public enum Columns {
	CONFIGURATION_ID("configurationId", 0), NOME("nome", 1), DATA_CREAZIONE(
		"dataCreazione", 2), AUTORE("autore", 3), VERSIONE("versione",
		4);

	String name;
	int num;

	private Columns(String name, int num) {
	    this.name = name;
	    this.num = num;
	}
    };

    public static String getName() {
	return TABLE_NAME;
    }

    // metodo per ottenere la query di creazione della tablla
    public static String getCreateQuery() {
	String createQuery = "CREATE TABLE IF NOT EXISTS "
		+ ConfigurationTable.TABLE_NAME + " ("
		+ Columns.CONFIGURATION_ID.toString()
		+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
		+ Columns.NOME.toString() + " TEXT UNIQUE NOT NULL, "
		+ Columns.DATA_CREAZIONE.toString() + " DATETIME NOT NULL, "
		+ Columns.AUTORE.toString() + " VARCHAR(20), "
		+ Columns.VERSIONE.toString() + " VARCHAR(10));";
	Log.d(log_class_name, "createQuery:" + createQuery);
	return createQuery;
    }

    // crea una nuova riga sul db con tutti i campi
    public static ContentValues createRecord(String nome) {

	ContentValues cv = new ContentValues();
	cv.put(Columns.NOME.toString(), nome);
	cv.put(Columns.DATA_CREAZIONE.toString(),
		new Timestamp(new GregorianCalendar(Locale.getDefault()).getTimeInMillis()).toString());
	cv.put(Columns.AUTORE.toString(), "io");
	cv.put(Columns.VERSIONE.toString(), "1.0");
	return cv;
    }

    public static String getKeyColumn() {
	return Columns.CONFIGURATION_ID.toString();
    }

    public static String[] getColumns() {
	String[] arrayTableColumns = { Columns.CONFIGURATION_ID.toString(),
		Columns.NOME.toString() };
	return arrayTableColumns;
    }

    public static Configuration getRecord(Cursor cursor) {
	Configuration config = new Configuration();
	config.setConfigurationId(Integer.parseInt(cursor
		.getString(Columns.CONFIGURATION_ID.num)));
	config.setNome(cursor.getString(Columns.NOME.num));
	config.setDataCreazione(Timestamp.valueOf(cursor
		.getString(Columns.DATA_CREAZIONE.num)));
	config.setAutore(cursor.getString(Columns.AUTORE.num));
	config.setVersione(cursor.getString(Columns.VERSIONE.num));
	Log.d(log_class_name, "[" + config.getConfigurationId()
		+ "] configuration: nome:" + config.getNome() + ", data:"
		+ config.getDataCreazione().toString());
	return config;
    }

}